const express = require('express');
const router = express.Router();
const { promiseQuery: query } = require('../db'); // 使用Promise风格的查询方法

// 获取教材列表（支持分页和筛选）
router.get('/', (req, res) => {
  const { page = 1, pageSize = 10, category_id, status, seller_id, search } = req.query;
  const offset = (page - 1) * pageSize;
  
  let sql = `
    SELECT t.*, c.name as category_name, u.username as seller_name
    FROM textbooks t
    LEFT JOIN categories c ON t.category_id = c.id
    LEFT JOIN users u ON t.seller_id = u.user_id
    WHERE 1=1
  `;
  const params = [];
  
  if (category_id) {
    sql += ' AND t.category_id = ?';
    params.push(category_id);
  }
  
  if (status) {
    sql += ' AND t.status = ?';
    params.push(status);
  }
  
  if (seller_id) {
    sql += ' AND t.seller_id = ?';
    params.push(seller_id);
  }
  
  if (search) {
    sql += ' AND (t.title LIKE ? OR t.author LIKE ? OR t.description LIKE ?)';
    const searchPattern = `%${search}%`;
    params.push(searchPattern, searchPattern, searchPattern);
  }
  
  sql += ' ORDER BY t.created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(pageSize), parseInt(offset));
  
  query(sql, params)
    .then(result => {
      // 解析images字段
      const data = result.map(item => {
        if (item.images) {
          try {
            item.images = JSON.parse(item.images);
          } catch (e) {
            item.images = [];
          }
        } else {
          item.images = [];
        }
        return item;
      });
      
      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM textbooks WHERE 1=1';
      const countParams = [];
      
      if (category_id) {
        countSql += ' AND category_id = ?';
        countParams.push(category_id);
      }
      if (status) {
        countSql += ' AND status = ?';
        countParams.push(status);
      }
      if (seller_id) {
        countSql += ' AND seller_id = ?';
        countParams.push(seller_id);
      }
      if (search) {
        countSql += ' AND (title LIKE ? OR author LIKE ? OR description LIKE ?)';
        const searchPattern = `%${search}%`;
        countParams.push(searchPattern, searchPattern, searchPattern);
      }
      
      return query(countSql, countParams).then(countResult => ({
        data,
        countResult
      }));
    })
    .then(({ data, countResult }) => {
      res.json({
        success: true,
        data: data,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: countResult[0].total
        }
      });
    })
    .catch(err => {
      console.error('Database error:', err);
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

// 根据ID获取教材详情
router.get('/:id', (req, res) => {
  const { id } = req.params;
  
  // 增加浏览量（异步，不阻塞主要请求）
  const updateViewsSql = 'UPDATE textbooks SET views = views + 1 WHERE id = ?';
  query(updateViewsSql, [id]).catch(err => console.error('Update views error:', err));
  
  const sql = `
    SELECT t.*, c.name as category_name, u.username as seller_name, u.phone as seller_phone
    FROM textbooks t
    LEFT JOIN categories c ON t.category_id = c.id
      LEFT JOIN users u ON t.seller_id = u.user_id
      WHERE t.id = ?
  `;
  
  query(sql, [id])
    .then(result => {
      if (result.length === 0) {
        return res.status(404).json({ 
          error: 'Textbook not found',
          message: `Textbook with ID ${id} does not exist`
        });
      }
      
      const textbook = result[0];
      if (textbook.images) {
        try {
          textbook.images = JSON.parse(textbook.images);
        } catch (e) {
          textbook.images = [];
        }
      } else {
        textbook.images = [];
      }
      
      res.json({
        success: true,
        data: textbook
      });
    })
    .catch(err => {
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

// 创建教材
router.post('/', (req, res) => {
  const { title, author, publisher, isbn, category_id, seller_id, description, price, original_price, condition, images, status } = req.body;
  
  if (!title || !seller_id || !price) {
    return res.status(400).json({
      error: 'Validation error',
      message: 'Title, seller_id and price are required'
    });
  }
  
  // 处理图片数据，限制图片数量和大小
  let processedImages = images || [];
  if (!Array.isArray(processedImages)) {
    processedImages = [processedImages];
  }
  // 限制最多5张图片
  processedImages = processedImages.slice(0, 5);
  // 优化每张图片数据
  const optimizedImages = processedImages.filter(img => {
    // 只保留有效的base64图片数据
    if (typeof img === 'string' && 
        img.startsWith('data:image/') && 
        img.includes(';base64,')) {
      // 检查数据长度是否合理（最长50000字符）
      return img.length <= 50000;
    }
    return false;
  });
  let imagesJson = JSON.stringify(optimizedImages);
  
  // 如果没有有效图片，设置为空数组
  if (optimizedImages.length === 0) {
    imagesJson = '[]';
  }
  
  const sql = `
    INSERT INTO textbooks 
    (title, author, publisher, isbn, category_id, seller_id, description, price, original_price, \`condition\`, images, status, created_at, updated_at) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
  `;
  const values = [
    title, author || null, publisher || null, isbn || null, 
    category_id || null, seller_id, description || null, 
    price, original_price || null, condition || 'good', 
    imagesJson, status || 'on_sale'
  ];
  
  query(sql, values)
    .then(result => {
      res.status(201).json({
        success: true,
        message: 'Textbook created successfully',
        data: {
          id: result.insertId,
          title,
          seller_id,
          price
        }
      });
    })
    .catch(err => {
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

// 更新教材
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { title, author, publisher, isbn, category_id, description, price, original_price, condition, images, status } = req.body;
  
  const updates = [];
  const values = [];
  
  if (title) { updates.push('title = ?'); values.push(title); }
  if (author !== undefined) { updates.push('author = ?'); values.push(author); }
  if (publisher !== undefined) { updates.push('publisher = ?'); values.push(publisher); }
  if (isbn !== undefined) { updates.push('isbn = ?'); values.push(isbn); }
  if (category_id !== undefined) { updates.push('category_id = ?'); values.push(category_id); }
  if (description !== undefined) { updates.push('description = ?'); values.push(description); }
  if (price) { updates.push('price = ?'); values.push(price); }
  if (original_price !== undefined) { updates.push('original_price = ?'); values.push(original_price); }
  if (condition) { updates.push('`condition` = ?'); values.push(condition); }
  if (images) {
    // 处理图片数据，限制图片数量和大小
    let processedImages = images;
    if (!Array.isArray(processedImages)) {
      processedImages = [processedImages];
    }
    // 限制最多5张图片
    processedImages = processedImages.slice(0, 5);
    // 优化每张图片数据
    const optimizedImages = processedImages.filter(img => {
      // 只保留有效的base64图片数据
      if (typeof img === 'string' && 
          img.startsWith('data:image/') && 
          img.includes(';base64,')) {
        // 检查数据长度是否合理（最长50000字符）
        return img.length <= 50000;
      }
      return false;
    });
    let imagesJson = JSON.stringify(optimizedImages);
    
    // 如果没有有效图片，设置为空数组
    if (optimizedImages.length === 0) {
      imagesJson = '[]';
    }
    
    updates.push('images = ?');
    values.push(imagesJson);
  }
  if (status) { updates.push('status = ?'); values.push(status); }
  
  if (updates.length === 0) {
    return res.status(400).json({
      error: 'Validation error',
      message: 'No fields to update'
    });
  }
  
  updates.push('updated_at = NOW()');
  values.push(id);
  
  const sql = `UPDATE textbooks SET ${updates.join(', ')} WHERE id = ?`;
  
  query(sql, values)
    .then(result => {
      if (result.affectedRows === 0) {
        return res.status(404).json({ 
          error: 'Textbook not found',
          message: `Textbook with ID ${id} does not exist`
        });
      }
      
      res.json({
        success: true,
        message: 'Textbook updated successfully'
      });
    })
    .catch(err => {
      console.error('Database error:', err);
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

// 删除教材
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  const sql = 'DELETE FROM textbooks WHERE id = ?';
  
  query(sql, [id])
    .then(result => {
      if (result.affectedRows === 0) {
        return res.status(404).json({ 
          error: 'Textbook not found',
          message: `Textbook with ID ${id} does not exist`
        });
      }
      
      res.json({
        success: true,
        message: 'Textbook deleted successfully'
      });
    })
    .catch(err => {
      console.error('Database error:', err);
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

// 获取分类列表
router.get('/categories', (req, res) => {
  const sql = 'SELECT * FROM categories ORDER BY sort_order ASC';
  
  query(sql)
    .then(result => {
      res.json({
        success: true,
        data: result
      });
    })
    .catch(err => {
      console.error('Database error:', err);
      res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    });
});

module.exports = router;